/*
 * @Author: 我想吃余 483766615@qq.com
 * @Date: 2025-10-19 16:54:57
 * @LastEditors: 我想吃余 483766615@qq.com
 * @LastEditTime: 2025-10-21 19:22:39
 * @FilePath: /code/oscode/fifo/comm.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "log.hpp"

#define SIZE 4096
#define PATHNAME "/home/zhh"
#define PROJ_ID 0x555

using namespace std;

Log log;

key_t GetKey()
{
    int key = ftok(PATHNAME, PROJ_ID);
    if(key < 0)
    {
        log(Fatal, "ftok error:%s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success,key is 0x%x", key);
    return key;
}

int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, SIZE, flag|0666);
    if(shmid < 0) 
    {
        log(Fatal, "shmget error:", strerror(errno));
        exit(2);
    }
    log(Info, "shmget success,shmid is %d", shmid);

    return shmid;
}

int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}


#define FIFO_FILE "./myfifo"
#define MODE 0664
#define NUM 1024

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        int n = mkfifo(FIFO_FILE, MODE);
        if(n == -1) 
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        int m = unlink(FIFO_FILE); 
        if(m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        } 
    }
};

